package com.linkwechat.wecom.factory.impl.kf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.tenant.TenantContextHolder;
import com.linkwechat.wecom.client.WeKfClient;
import com.linkwechat.wecom.domain.*;
import com.linkwechat.wecom.domain.dto.WeResultDto;
import com.linkwechat.wecom.domain.dto.kf.*;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeEventStrategy;
import com.linkwechat.wecom.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Administrator on 2022-1-15.
 */
@Slf4j
@Component("kf_msg_or_event")
public class WeCallbackSyncMsgImpl extends WeEventStrategy {
    @Autowired
    WeKfClient weKfClient;

    @Autowired
    private RedisCache cursorCache;    //分页标志位

    @Autowired
    //private RedisCache servicePersonCache;    //客服人员(会话分配失败时标记)

    @Resource
    WeworkKfServicerMapper weworkKfServicerMapper;

    @Resource
    WeworkKfLogMapper weworkKfLogMapper;

    @Resource
    WeworkKfCustomerMapper weworkKfCustomerMapper;

    @Resource
    WeworkKfRelationMapper weworkKfRelationMapper;

    @Resource
    WeworkKfMemberRelationMapper weworkKfMemberRelationMapper;

    @Override
    public void eventHandle(WxCpXmlMessageVO message) {
        //获取会话状态
        ServiceStateGetDto serviceStateGetDto = new ServiceStateGetDto();
        ServiceStateGetResDto serviceStateGetResDto;

        //读取消息
        SyncMsgDto syncMsgDto = new SyncMsgDto();
        syncMsgDto.setToken(message.getToken());
        syncMsgDto.setLimit(5);
        SyncMsgResDto syncMsgResDto;

        //接待人员
        ServicerListResDto servicerListResDto;
        //添加或删除接待人员
        ServicerDto servicerDto = new ServicerDto();
        //获取客服账号下的接待人员
        OpenKfidDto openKfidDto = new OpenKfidDto();
        List<ServicerUserDto> servicerUserDtoList;

        //变更会话状态
        ServiceStateTransDto serviceStateTransDto = new ServiceStateTransDto();
        ServiceStateTransResDto serviceStateTransResDto;

//        try {
            WeKfSyncMsgEvent weKfSyncMsgEvent;
            WeworkKfServicer weworkKfServicer;
            WeworkKfCustomer weworkKfCustomer = null;
            WeworkKfRelation weworkKfRelation;
            WeworkKfLog weworkKfLog;

            String memberId;  //接待人员助销宝memberId
            String mobile;    //客户手机号
            String userid;    //接待人员userid

            String tenanntCode = TenantContextHolder.getTenantCode();
            int hasMore = 1;
            do {
                //获取最近的标志位
                if (cursorCache.getCacheObject(tenanntCode) != null) {
                    syncMsgDto.setCursor(cursorCache.getCacheObject(tenanntCode));
                }

                //读取消息
                syncMsgResDto = weKfClient.syncMsg(syncMsgDto);
                if (syncMsgResDto.getErrcode() == 0) {
                    WeworkKfMemberRelation weworkMemberRelation;    //接待人员助销宝memberId与userid桥接表
                    List<WekfSyncMsgModel> msgList = syncMsgResDto.getMsgList();
                    for (WekfSyncMsgModel m : msgList) {
                        try {
                            userid = null;
                            mobile = null;
                            if (m.getMsgtype().equals("event")) {    //事件
                                weKfSyncMsgEvent = m.getEvent();

                                //事件分支
                                if (weKfSyncMsgEvent.getEventType().equals("enter_session")) {    //进入会话状态
                                    //此事件分支的日志
                                    weworkKfLog = new WeworkKfLog();
                                    weworkKfLog.setEventType(weKfSyncMsgEvent.getEventType());
                                    weworkKfLog.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                    //weworkKfLog.setServicerId(weworkKfServicer.getId());
                                    weworkKfLog.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                    weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                    weworkKfLog.setMsgid(m.getMsgid());

                                    boolean hasServicerInfo;
                                    //判断是否含有自定义参数
                                    if (weKfSyncMsgEvent.getSceneParam() != null) {    //助销宝电子名片入口(一对一)
                                        hasServicerInfo = true;
                                        String split[] = weKfSyncMsgEvent.getSceneParam().split(",");
                                        memberId = split[0];
                                        if (split.length > 1) {
                                            mobile = split[1];
                                        }

                                        //根据桥接表获取接待人员userid
                                        weworkMemberRelation = weworkKfMemberRelationMapper.selectByMemberId(Integer.valueOf(memberId));
                                        //判断桥接表中是否能找到
                                        if (weworkMemberRelation == null || weworkMemberRelation.getState() == 0) {
                                            //未能找到桥接表对应的userid，原因为接待人员未注册企微，或在企微中未绑定手机号
                                            weworkKfLog.setSysTime(new Date());
                                            weworkKfLog.setNote("获取接待人员userid失败——未能找到桥接表对应的userid,memberId:" + memberId + ",mobile:" + mobile);
                                            weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                        } else {
                                            userid = weworkMemberRelation.getUserid();
                                        }

                                    } else {    //外部场景入口(一对多)
                                        hasServicerInfo = false;
                                        //判断之前此前是否已有过对接
                                        Map customerMap = new HashMap<>();
                                        customerMap.put("external_userid", weKfSyncMsgEvent.getExternalUserid());
                                        customerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                        List<WeworkKfCustomer> weworkKfCustomerList = weworkKfCustomerMapper.selectByMap(customerMap);
                                        if (weworkKfCustomerList.size() == 0) {    //新增客户
                                            //获取客服账号下的所有接待人员
                                            openKfidDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                            servicerListResDto = weKfClient.getServicerList(openKfidDto.getOpen_kfid());
                                            if (servicerListResDto.getErrcode() == 0) {
                                                servicerUserDtoList = servicerListResDto.getServicer_list();
                                                if (servicerUserDtoList != null && servicerUserDtoList.size() > 0) {
                                                    //时间戳对列表长度除余
                                                    int index = Integer.valueOf(String.valueOf(m.getSendTime() % servicerUserDtoList.size()));
                                                    userid = servicerUserDtoList.get(index).getUserid();

                                                    weworkKfCustomer = new WeworkKfCustomer();
                                                    weworkKfCustomer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                    weworkKfCustomer.setExternalUserid(weKfSyncMsgEvent.getExternalUserid());
                                                    weworkKfCustomer.setCurrentServicerId(userid);    //需事先标记，以便在分配失败后依据此id重新分配
                                                    weworkKfCustomer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                    //获取客户的会话状态(每次都确认此状态)
                                                    serviceStateGetDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                    serviceStateGetDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                    serviceStateGetResDto = weKfClient.getServiceState(serviceStateGetDto);
                                                    if (serviceStateGetResDto.getErrcode() == 0) {
                                                        //客户状态
                                                        weworkKfCustomer.setStatus(serviceStateGetResDto.getServiceState());
                                                    } else {
                                                        weworkKfCustomer.setStatus(0);

                                                        weworkKfLog.setSysTime(new Date());
                                                        weworkKfLog.setNote("获取客户会话状态失败——" + serviceStateGetResDto.getErrcode().toString() + ": " + serviceStateGetResDto.getErrmsg());
                                                        weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                    }
                                                    weworkKfCustomerMapper.insertWeworkKfCustomer(weworkKfCustomer);

                                                    //重新获取数据（主键id）
                                                    weworkKfCustomer = (WeworkKfCustomer) weworkKfCustomerMapper.selectByMap(customerMap).get(0);
                                                }

                                            } else {
                                                weworkKfLog.setNote("获取接待人员列表失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                            }

                                        } else {
                                            weworkKfCustomer = weworkKfCustomerList.get(0);
                                            //weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));

                                            //获取上一个对接的接待人员
                                            userid = weworkKfCustomer.getCurrentServicerId();

                                            //获取客户的会话状态(每次都确认此状态)
                                            serviceStateGetDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                            serviceStateGetDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                            serviceStateGetResDto = weKfClient.getServiceState(serviceStateGetDto);
                                            if (serviceStateGetResDto.getErrcode() == 0) {
                                                //客户状态
                                                weworkKfCustomer.setStatus(serviceStateGetResDto.getServiceState());
                                            } else {
                                                weworkKfCustomer.setStatus(0);

                                                weworkKfLog.setSysTime(new Date());
                                                weworkKfLog.setNote("获取客户会话状态失败——" + serviceStateGetResDto.getErrcode().toString() + ": " + serviceStateGetResDto.getErrmsg());
                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                            }
                                            weworkKfCustomerMapper.updateStatus(weworkKfCustomer);
                                        }

                                    }

                                    if (userid != null) {
                                        //weworkKfCustomer = null;
                                        if (hasServicerInfo) {
                                            //判断客户是否存在
    //                                      QueryWrapper<WeworkKfCustomer> wrapperKfCustomer = new QueryWrapper<>();
    //                                      wrapperKfCustomer.eq("external_userid", weKfSyncMsgEvent.getExternalUserid()).eq("open_kfid", weKfSyncMsgEvent.getOpenKfid());
    //                                      weworkKfCustomer = weworkKfCustomerMapper.selectOne(wrapperKfCustomer);

                                            Map customerMap = new HashMap<>();
                                            customerMap.put("external_userid", weKfSyncMsgEvent.getExternalUserid());
                                            customerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                            List<WeworkKfCustomer> weworkKfCustomerList = weworkKfCustomerMapper.selectByMap(customerMap);
                                            if (weworkKfCustomerList.size() == 0) {    //新增客户
                                                weworkKfCustomer = new WeworkKfCustomer();
                                                weworkKfCustomer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                weworkKfCustomer.setExternalUserid(weKfSyncMsgEvent.getExternalUserid());
                                                weworkKfCustomer.setMobile(mobile);
                                                weworkKfCustomer.setCurrentServicerId(userid);    //需事先标记，以便在分配失败后依据此id重新分配
                                                weworkKfCustomer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                //获取客户的会话状态(每次都确认此状态)
                                                serviceStateGetDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                serviceStateGetDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                serviceStateGetResDto = weKfClient.getServiceState(serviceStateGetDto);
                                                if (serviceStateGetResDto.getErrcode() == 0) {
                                                    //客户状态
                                                    weworkKfCustomer.setStatus(serviceStateGetResDto.getServiceState());
                                                } else {
                                                    weworkKfCustomer.setStatus(0);

                                                    weworkKfLog.setSysTime(new Date());
                                                    weworkKfLog.setNote("获取客户会话状态失败——" + serviceStateGetResDto.getErrcode().toString() + ": " + serviceStateGetResDto.getErrmsg());
                                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                }
                                                weworkKfCustomerMapper.insertWeworkKfCustomer(weworkKfCustomer);

                                                //重新获取数据（主键id）
                                                weworkKfCustomer = (WeworkKfCustomer) weworkKfCustomerMapper.selectByMap(customerMap).get(0);
                                            } else {
                                                weworkKfCustomer = weworkKfCustomerList.get(0);
                                                weworkKfCustomer.setMobile(mobile);
                                                weworkKfCustomer.setCurrentServicerId(userid);    //需事先标记，以便在分配失败后依据此id重新分配
                                                //weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));

                                                //获取客户的会话状态(每次都确认此状态)
                                                serviceStateGetDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                serviceStateGetDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                serviceStateGetResDto = weKfClient.getServiceState(serviceStateGetDto);
                                                if (serviceStateGetResDto.getErrcode() == 0) {
                                                    //客户状态
                                                    weworkKfCustomer.setStatus(serviceStateGetResDto.getServiceState());
                                                } else {
                                                    weworkKfCustomer.setStatus(0);

                                                    weworkKfLog.setSysTime(new Date());
                                                    weworkKfLog.setNote("获取客户会话状态失败——" + serviceStateGetResDto.getErrcode().toString() + ": " + serviceStateGetResDto.getErrmsg());
                                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                }
                                                weworkKfCustomerMapper.updateStatus(weworkKfCustomer);
                                            }

                                        }

                                        //判断接待人员是否存在
    //                                        QueryWrapper<WeworkKfServicer> wrapperKfServicer = new QueryWrapper<>();
    //                                        wrapperKfServicer.eq("userid", userid).eq("open_kfid", weKfSyncMsgEvent.getOpenKfid());
    //                                        weworkKfServicer = weworkKfServicerMapper.selectOne(wrapperKfServicer);

                                        //接待人员
                                        weworkKfServicer = null;
                                        Map servicerMap = new HashMap<>();
                                        servicerMap.put("userid", userid);
                                        servicerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                        List<WeworkKfServicer> weworkKfServicerList = weworkKfServicerMapper.selectByMap(servicerMap);
                                        if (weworkKfServicerList.size() == 0) {    //添加接待人员
                                            //新增API
                                            servicerDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                            List<String> ul = new ArrayList<>();
                                            ul.add(userid);
                                            servicerDto.setUserid_list(ul);

                                            servicerListResDto = weKfClient.addServicer(servicerDto);
                                            //新增成功
                                            if (servicerListResDto.getErrcode() == 0) {
                                                weworkKfServicer = new WeworkKfServicer();
                                                weworkKfServicer.setUserid(userid);
                                                weworkKfServicer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                weworkKfServicer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfServicer.setStatus(1);
                                                weworkKfServicer.setIsActivate(1);
                                                weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);

                                                //重新获取数据（主键id）
                                                weworkKfServicer = (WeworkKfServicer) weworkKfServicerMapper.selectByMap(servicerMap).get(0);

                                            } else {
                                                //如果是随机分配的情况，可能因为上一名接待人员已经不在客服账号中
                                                if (!hasServicerInfo) {
                                                    //获取客服账号下的所有接待人员
                                                    openKfidDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                    servicerListResDto = weKfClient.getServicerList(openKfidDto.getOpen_kfid());
                                                    if (servicerListResDto.getErrcode() == 0) {
                                                        servicerUserDtoList = servicerListResDto.getServicer_list();
                                                        if (servicerUserDtoList != null && servicerUserDtoList.size() > 0) {
                                                            //时间戳对列表长度除余
                                                            int index = Integer.valueOf(String.valueOf(m.getSendTime() % servicerUserDtoList.size()));
                                                            userid = servicerUserDtoList.get(index).getUserid();

                                                            //再次尝试分配
                                                            ul = new ArrayList<>();
                                                            ul.add(userid);
                                                            servicerDto.setUserid_list(ul);
                                                            servicerListResDto = weKfClient.addServicer(servicerDto);
                                                            //新增成功
                                                            if (servicerListResDto.getErrcode() == 0) {
                                                                weworkKfServicer = new WeworkKfServicer();
                                                                weworkKfServicer.setUserid(userid);
                                                                weworkKfServicer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                                weworkKfServicer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                                weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                                weworkKfServicer.setStatus(1);
                                                                weworkKfServicer.setIsActivate(1);
                                                                weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);

                                                                //重新获取数据（主键id）
                                                                weworkKfServicer = (WeworkKfServicer) weworkKfServicerMapper.selectByMap(servicerMap).get(0);

                                                            } else {
                                                                weworkKfLog.setSysTime(new Date());
                                                                weworkKfLog.setNote("添加接待人员失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                            }

                                                        } else {
                                                            weworkKfLog.setNote("获取接待人员列表失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                            weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                        }

                                                    }

                                                }

                                            }

                                        } else {
                                            weworkKfServicer = weworkKfServicerList.get(0);

                                            if (weworkKfServicer.getIsActivate() == 0) {    //未激活
                                                //再次添加接待人员
                                                servicerDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                List<String> ul = new ArrayList<>();
                                                ul.add(userid);
                                                servicerDto.setUserid_list(ul);

                                                servicerListResDto = weKfClient.addServicer(servicerDto);
                                                //新增成功
                                                if (servicerListResDto.getErrcode() == 0) {
                                                    weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfServicer.setIsActivate(1);
                                                    weworkKfServicerMapper.updateStatus(weworkKfServicer);
                                                } else {
                                                    //如果是随机分配的情况(可能接待人员已不存在)
                                                    if (!hasServicerInfo) {
                                                        //获取客服账号下的所有接待人员
                                                        openKfidDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                        servicerListResDto = weKfClient.getServicerList(openKfidDto.getOpen_kfid());
                                                        if (servicerListResDto.getErrcode() == 0) {
                                                            servicerUserDtoList = servicerListResDto.getServicer_list();
                                                            if (servicerUserDtoList != null && servicerUserDtoList.size() > 0) {
                                                                //时间戳对列表长度除余
                                                                int index = Integer.valueOf(String.valueOf(m.getSendTime() % servicerUserDtoList.size()));
                                                                userid = servicerUserDtoList.get(index).getUserid();

                                                                //再次尝试分配
                                                                ul = new ArrayList<>();
                                                                ul.add(userid);
                                                                servicerDto.setUserid_list(ul);
                                                                servicerListResDto = weKfClient.addServicer(servicerDto);
                                                                //新增成功
                                                                if (servicerListResDto.getErrcode() == 0) {
                                                                    weworkKfServicer = new WeworkKfServicer();
                                                                    weworkKfServicer.setUserid(userid);
                                                                    weworkKfServicer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                                    weworkKfServicer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                                    weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                                    weworkKfServicer.setStatus(1);
                                                                    weworkKfServicer.setIsActivate(1);
                                                                    weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);

                                                                    //重新获取数据（主键id）
                                                                    weworkKfServicer = (WeworkKfServicer) weworkKfServicerMapper.selectByMap(servicerMap).get(0);

                                                                } else {
                                                                    weworkKfLog.setSysTime(new Date());
                                                                    weworkKfLog.setNote("添加接待人员失败(曾被添加)——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                                }

                                                            } else {
                                                                weworkKfLog.setNote("获取接待人员列表失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                            }

                                                        }

                                                    }

                                                }
                                            }

                                        }

                                        //接待人员状态正常
                                        if (weworkKfServicer != null && weworkKfCustomer.getStatus() != 4/*状态4无法分配，需等用户发送一条消息后方可成功*/) {
                                            weworkKfLog.setServicerId(userid);
                                            if (weworkKfServicer.getStatus() == 1) {
                                                //分配会话
                                                serviceStateTransDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                serviceStateTransDto.setService_state(3);
                                                serviceStateTransDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                serviceStateTransDto.setServicer_userid(userid);

                                                serviceStateTransResDto = weKfClient.transServiceState(serviceStateTransDto);

                                                if (serviceStateTransResDto.getErrcode() == 0) {    //分配成功
                                                    //标记客户状态为"会话中"
                                                    weworkKfCustomer.setStatus(3);

                                                    //客户与客服关联(分配成功才关联)
    //                                                QueryWrapper<WeworkKfRelation> wrapperKfRelation = new QueryWrapper<>();
    //                                                wrapperKfRelation.eq("servicer_id", userid).eq("customer_id", weKfSyncMsgEvent.getExternalUserid());
    //                                                weworkKfRelation = weworkKfRelationMapper.selectOne(wrapperKfRelation);

                                                    Map weworkKfRelationMap = new HashMap<>();
                                                    weworkKfRelationMap.put("servicer_id", userid);
                                                    weworkKfRelationMap.put("customer_id", weKfSyncMsgEvent.getExternalUserid());
                                                    weworkKfRelationMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                                    List<WeworkKfRelation> weworkKfRelationList = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);
                                                    if (weworkKfRelationList.size() == 0) {
                                                        weworkKfRelation = new WeworkKfRelation();
                                                        weworkKfRelation.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                        weworkKfRelation.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                                        weworkKfRelation.setServicerId(userid);
                                                        weworkKfRelation.setCreateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelationMapper.insert(weworkKfRelation);

                                                        //重新获取
                                                        weworkKfRelation = (WeworkKfRelation) weworkKfRelationMapper.selectByMap(weworkKfRelationMap).get(0);
                                                    } else {
                                                        weworkKfRelation = weworkKfRelationList.get(0);
                                                        weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelationMapper.updateStatus(weworkKfRelation);
                                                    }

                                                    //分配专属客服(同客服账号下所有成员)
                                                    if (weworkKfRelation.getIsUpgradeMember()==0) {
                                                        UpgradeServicerDto upgradeServiceDto = new UpgradeServicerDto();
                                                        upgradeServiceDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                        upgradeServiceDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                        upgradeServiceDto.setType(1);

                                                        UpGradeServiceMember upGradeServiceMember = new UpGradeServiceMember();
                                                        upGradeServiceMember.setUserid(userid);
                                                        upgradeServiceDto.setMember(upGradeServiceMember);

                                                        WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
                                                        if(weResultDto.getErrcode()==0){
                                                            weworkKfRelation.setIsUpgradeMember(1);
                                                            weworkKfRelationMapper.updateById(weworkKfRelation);

                                                            //将同客服账号下其余接待人员升级标志位置零
                                                            weworkKfRelationMapper.resetUpgradeMember(weworkKfRelation);
                                                        }
                                                    }


    //                                                List<WeworkKfServicer> weworkKfServicerList2 = weworkKfServicerMapper.selectAllUserByOpenKfid(weworkKfServicer);
    //                                                for(WeworkKfServicer weworkKfServicer2: weworkKfServicerList2){
    //                                                    weworkKfRelationMap.put("servicer_id", weworkKfServicer2.getUserid());
    //                                                    List<WeworkKfRelation> weworkKfRelationList2 = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);
    //                                                    if(weworkKfRelationList2.size()==0) {
    //                                                        upGradeServiceMember.setUserid(weworkKfServicer2.getUserid());
    //                                                        upgradeServiceDto.setMember(upGradeServiceMember);
    //                                                        WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
    //                                                        if(weResultDto.getErrcode()==0){
    //                                                            weworkKfRelation = new WeworkKfRelation();
    //                                                            weworkKfRelation.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
    //                                                            weworkKfRelation.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
    //                                                            weworkKfRelation.setServicerId(weworkKfServicer2.getUserid());
    //                                                            weworkKfRelation.setIsUpgradeMember(1);
    //                                                            weworkKfRelationMapper.insert(weworkKfRelation);
    //                                                        }
    //
    //                                                    } else if (weworkKfRelationList2.get(0).getIsUpgradeMember()==0) {
    //                                                        upGradeServiceMember.setUserid(weworkKfServicer2.getUserid());
    //                                                        upgradeServiceDto.setMember(upGradeServiceMember);
    //                                                        WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
    //                                                        if(weResultDto.getErrcode()==0){
    //                                                            weworkKfRelation = weworkKfRelationList.get(0);
    //                                                            weworkKfRelation.setIsUpgradeMember(1);
    //                                                            weworkKfRelationMapper.updateById(weworkKfRelation);
    //                                                        }
    //
    //                                                    }
    //
    //                                                }

                                                } else {    //分配失败
                                                    weworkKfLog.setNote("分配客户失败——" + serviceStateTransResDto.getErrcode().toString() + ": " + serviceStateTransResDto.getErrmsg());

                                                    //此处酌情处理(暂将所有分配异常客户状态置0)
                                                    //weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfCustomer.setStatus(0);
                                                }

                                                weworkKfCustomerMapper.updateStatus(weworkKfCustomer);

                                                weworkKfLog.setSysTime(new Date());

                                            } else {
                                                //记录此情形
                                                weworkKfLog.setSysTime(new Date());
                                                weworkKfLog.setNote("分配客户失败——接待人员不在接待状态");

                                            }

                                            weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                        }

                                    }


                                } else if (weKfSyncMsgEvent.getEventType().equals("msg_send_fail")) {    //消息发送失败事件
                                    weworkKfLog = new WeworkKfLog();
                                    weworkKfLog.setEventType(weKfSyncMsgEvent.getEventType());
                                    weworkKfLog.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                    weworkKfLog.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                    weworkKfLog.setFailType(weKfSyncMsgEvent.getFailType());
                                    weworkKfLog.setFailMsgid(weKfSyncMsgEvent.getFailMsgid());
                                    weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                    weworkKfLog.setSysTime(new Date());
                                    weworkKfLog.setMsgid(m.getMsgid());
                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                    //重新分配会话
                                    if (weKfSyncMsgEvent.getFailType() != 1/*客服账号已删除*/) {
                                        //客服账号+客户ID
                                        //String kf_account_external_userid = weKfSyncMsgEvent.getOpenKfid() + "_" + weKfSyncMsgEvent.getExternalUserid();

                                        //获取对应的接待人员userid
                                        //serviceStateTransDto.setServicer_userid(servicePersonCache.getCacheObject(kf_account_external_userid));
    //                                QueryWrapper<WeworkKfCustomer> wrapperKfCustomer = new QueryWrapper<>();
    //                                wrapperKfCustomer.eq("external_userid", weKfSyncMsgEvent.getExternalUserid()).eq("open_kfid", weKfSyncMsgEvent.getOpenKfid());
    //                                weworkKfCustomer = weworkKfCustomerMapper.selectOne(wrapperKfCustomer);

                                        Map customerMap = new HashMap<>();
                                        customerMap.put("external_userid", weKfSyncMsgEvent.getExternalUserid());
                                        customerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                        List<WeworkKfCustomer> weworkKfCustomerList = weworkKfCustomerMapper.selectByMap(customerMap);
                                        if (weworkKfCustomerList.size() > 0 && (weworkKfCustomerList.get(0).getStatus() == 4 || weworkKfCustomerList.get(0).getStatus() == 0)) {
                                            weworkKfCustomer = weworkKfCustomerList.get(0);
                                            //定义为进入会话事件
                                            weworkKfLog = new WeworkKfLog();
                                            weworkKfLog.setEventType("enter_session");
                                            weworkKfLog.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                            weworkKfLog.setServicerId(weworkKfCustomer.getCurrentServicerId());
                                            weworkKfLog.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                            weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                            //weworkKfLog.setMsgid(m.getMsgid());

                                            //接待人员
                                            weworkKfServicer = null;
                                            Map servicerMap = new HashMap<>();
                                            servicerMap.put("userid", weworkKfCustomer.getCurrentServicerId());
                                            servicerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                            List<WeworkKfServicer> weworkKfServicerList = weworkKfServicerMapper.selectByMap(servicerMap);
                                            if (weworkKfServicerList.size() == 0) {    //添加接待人员
                                                //新增API
                                                servicerDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                List<String> ul = new ArrayList<>();
                                                ul.add(weworkKfCustomer.getCurrentServicerId());
                                                servicerDto.setUserid_list(ul);

                                                servicerListResDto = weKfClient.addServicer(servicerDto);
                                                //新增成功
                                                if (servicerListResDto.getErrcode() == 0) {
                                                    weworkKfServicer = new WeworkKfServicer();
                                                    weworkKfServicer.setUserid(weworkKfCustomer.getCurrentServicerId());
                                                    weworkKfServicer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                    weworkKfServicer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfServicer.setStatus(1);
                                                    weworkKfServicer.setIsActivate(1);
                                                    weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);

                                                    //重新获取数据（主键id）
                                                    weworkKfServicer = (WeworkKfServicer) weworkKfServicerMapper.selectByMap(servicerMap).get(0);

                                                } else {
                                                    weworkKfLog.setSysTime(new Date());
                                                    weworkKfLog.setNote("添加接待人员失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                                }

                                            } else {
                                                weworkKfServicer = weworkKfServicerList.get(0);

                                                if (weworkKfServicer.getIsActivate() == 0) {    //未激活
                                                    //再次添加接待人员
                                                    servicerDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                    List<String> ul = new ArrayList<>();
                                                    ul.add(weworkKfCustomer.getCurrentServicerId());
                                                    servicerDto.setUserid_list(ul);

                                                    servicerListResDto = weKfClient.addServicer(servicerDto);
                                                    //新增成功
                                                    if (servicerListResDto.getErrcode() == 0) {
                                                        weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfServicer.setIsActivate(1);
                                                        weworkKfServicerMapper.updateStatus(weworkKfServicer);
                                                    } else {
                                                        weworkKfLog.setSysTime(new Date());
                                                        weworkKfLog.setNote("添加接待人员失败(曾被添加)——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                        weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                    }
                                                }

                                            }

                                            //接待人员状态正常
                                            if (weworkKfServicer != null) {
                                                if (weworkKfServicer.getStatus() == 1) {
                                                    //分配会话
                                                    serviceStateTransDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                    serviceStateTransDto.setService_state(3);
                                                    serviceStateTransDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                    serviceStateTransDto.setServicer_userid(weworkKfCustomer.getCurrentServicerId());
                                                    serviceStateTransResDto = weKfClient.transServiceState(serviceStateTransDto);
                                                    if (serviceStateTransResDto.getErrcode() == 0) {    //分配成功
                                                        //标记客户状态为"会话中"，并标记当前所属客服
                                                        weworkKfCustomer.setCurrentServicerId(weworkKfCustomer.getCurrentServicerId());
                                                        weworkKfCustomer.setStatus(3);
                                                        weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));

                                                        //客户与客服关联(分配成功才关联)
    //                                        QueryWrapper<WeworkKfRelation> wrapperKfRelation = new QueryWrapper<>();
    //                                        wrapperKfRelation.eq("servicer_id", weworkKfCustomer.getCurrentServicerId()).eq("customer_id", weKfSyncMsgEvent.getExternalUserid());
    //                                        weworkKfRelation = weworkKfRelationMapper.selectOne(wrapperKfRelation);

                                                        Map weworkKfRelationMap = new HashMap<>();
                                                        weworkKfRelationMap.put("servicer_id", weworkKfCustomer.getCurrentServicerId());
                                                        weworkKfRelationMap.put("customer_id", weKfSyncMsgEvent.getExternalUserid());
                                                        weworkKfRelationMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                                        List<WeworkKfRelation> weworkKfRelationList = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);
                                                        if (weworkKfRelationList.size() == 0) {
                                                            weworkKfRelation = new WeworkKfRelation();
                                                            weworkKfRelation.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                            weworkKfRelation.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                                            weworkKfRelation.setServicerId(weworkKfCustomer.getCurrentServicerId());
                                                            weworkKfRelation.setCreateTime(new Date(m.getSendTime() * 1000));
                                                            weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                            weworkKfRelationMapper.insert(weworkKfRelation);

                                                            //重新获取
                                                            weworkKfRelation = (WeworkKfRelation) weworkKfRelationMapper.selectByMap(weworkKfRelationMap).get(0);

                                                        } else {
                                                            weworkKfRelation = weworkKfRelationList.get(0);
                                                            weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                            weworkKfRelationMapper.updateStatus(weworkKfRelation);
                                                        }

                                                        //分配专属客服(同客服账号下所有成员)
                                                        if (weworkKfRelation.getIsUpgradeMember()==0) {
                                                            UpgradeServicerDto upgradeServiceDto = new UpgradeServicerDto();
                                                            upgradeServiceDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                            upgradeServiceDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                            upgradeServiceDto.setType(1);

                                                            UpGradeServiceMember upGradeServiceMember = new UpGradeServiceMember();
                                                            upGradeServiceMember.setUserid(userid);
                                                            upgradeServiceDto.setMember(upGradeServiceMember);

                                                            WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
                                                            if(weResultDto.getErrcode()==0){
                                                                weworkKfRelation.setIsUpgradeMember(1);
                                                                weworkKfRelationMapper.updateById(weworkKfRelation);

                                                                //将同客服账号下其余接待人员升级标志位置零
                                                                weworkKfRelationMapper.resetUpgradeMember(weworkKfRelation);
                                                            }
                                                        }

                                                    } else {    //分配失败
                                                        weworkKfLog.setNote("分配客户失败——" + serviceStateTransResDto.getErrcode().toString() + ": " + serviceStateTransResDto.getErrmsg());

                                                        //此处酌情处理(暂将所有分配异常客户状态置0)
                                                        //weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfCustomer.setStatus(0);
                                                    }

                                                    weworkKfCustomerMapper.updateStatus(weworkKfCustomer);

                                                    weworkKfLog.setSysTime(new Date());

                                                } else {
                                                    //记录此情形
                                                    weworkKfLog.setSysTime(new Date());
                                                    weworkKfLog.setNote("分配客户失败——接待人员不在接待状态");
                                                }
                                            }

                                            weworkKfLog.setSysTime(new Date());
                                            weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                        }

                                    }

                                } else if (weKfSyncMsgEvent.getEventType().equals("servicer_status_change")) {    //接待人员接待状态变更事件
                                    weworkKfLog = new WeworkKfLog();
                                    weworkKfLog.setEventType(weKfSyncMsgEvent.getEventType());
                                    weworkKfLog.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                    weworkKfLog.setServicerId(weKfSyncMsgEvent.getServicerUserid());
                                    weworkKfLog.setServicerStatus(weKfSyncMsgEvent.getStatus());
                                    weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                    weworkKfLog.setSysTime(new Date());
                                    weworkKfLog.setMsgid(m.getMsgid());
                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                    //接待人员状态变化
                                    weworkKfServicer = new WeworkKfServicer();
                                    weworkKfServicer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                    weworkKfServicer.setUserid(weKfSyncMsgEvent.getServicerUserid());
                                    weworkKfServicer.setStatus(weKfSyncMsgEvent.getStatus());
                                    weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                    weworkKfServicerMapper.updateStatus(weworkKfServicer);

                                } else if (weKfSyncMsgEvent.getEventType().equals("session_status_change")) {    //会话状态变更事件
                                    weworkKfLog = new WeworkKfLog();
                                    weworkKfLog.setEventType(weKfSyncMsgEvent.getEventType());
                                    weworkKfLog.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                    weworkKfLog.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                    weworkKfLog.setChangeType(weKfSyncMsgEvent.getChangeType());
                                    if (weKfSyncMsgEvent.getChangeType() != 1) {
                                        weworkKfLog.setOldServicerUserid(weKfSyncMsgEvent.getOldServicerUserid());
                                    }
                                    if (weKfSyncMsgEvent.getChangeType() != 3) {
                                        weworkKfLog.setNewServicerUserid(weKfSyncMsgEvent.getNewServicerUserid());
                                    }
                                    weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                    weworkKfLog.setSysTime(new Date());
                                    weworkKfLog.setMsgid(m.getMsgid());
                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                    //会话状态变化
                                /*weworkKfCustomer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                weworkKfCustomer.setExternalUserid(weKfSyncMsgEvent.getExternalUserid());*/
                                    //获取客户（状态变化下，客户应已存在）
                                    Map customerMap = new HashMap<>();
                                    customerMap.put("external_userid", weKfSyncMsgEvent.getExternalUserid());
                                    customerMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                    List<WeworkKfCustomer> weworkKfCustomerList = weworkKfCustomerMapper.selectByMap(customerMap);
                                    if (weworkKfCustomerList.size() > 0) {
                                        weworkKfCustomer = weworkKfCustomerList.get(0);
                                        weworkKfCustomer.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                        weworkKfCustomer.setExternalUserid(weKfSyncMsgEvent.getExternalUserid());
                                        weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                        if (weKfSyncMsgEvent.getChangeType() == 3) {    //会话结束（接待人员从客户端操作）
                                            weworkKfCustomer.setStatus(4);
                                        } else {    //接入会话（各种来源）
                                            //客户状态变化
                                            weworkKfCustomer.setCurrentServicerId(weKfSyncMsgEvent.getNewServicerUserid());
                                            weworkKfCustomer.setStatus(3);

                                            //新会话客服人员
                                            //                                QueryWrapper<WeworkKfServicer> wrapperKfServicer = new QueryWrapper<>();
                                            //                                wrapperKfServicer = new QueryWrapper<>();
                                            //                                wrapperKfServicer.eq("userid", weKfSyncMsgEvent.getNewServicerUserid()).eq("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                            //                                weworkKfServicer = weworkKfServicerMapper.selectOne(wrapperKfServicer);
                                            //                                if (weworkKfServicer != null) {
                                            //                                    weworkKfCustomer.setCurrentServicerId(weworkKfServicer.getId());
                                            //                                }

                                            //客户与客服关联
                                            //                                QueryWrapper<WeworkKfRelation> wrapperKfRelation = new QueryWrapper<>();
                                            //                                wrapperKfRelation.eq("servicer_id", weKfSyncMsgEvent.getNewServicerUserid()).eq("customer_id", weKfSyncMsgEvent.getExternalUserid());
                                            //                                weworkKfRelation = weworkKfRelationMapper.selectOne(wrapperKfRelation);

                                            Map weworkKfRelationMap = new HashMap<>();
                                            weworkKfRelationMap.put("servicer_id", weKfSyncMsgEvent.getNewServicerUserid());
                                            weworkKfRelationMap.put("customer_id", weKfSyncMsgEvent.getExternalUserid());
                                            weworkKfRelationMap.put("open_kfid", weKfSyncMsgEvent.getOpenKfid());
                                            List<WeworkKfRelation> weworkKfRelationList = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);
                                            if (weworkKfRelationList.size() == 0) {
                                                weworkKfRelation = new WeworkKfRelation();
                                                weworkKfRelation.setOpenKfid(weKfSyncMsgEvent.getOpenKfid());
                                                weworkKfRelation.setCustomerId(weKfSyncMsgEvent.getExternalUserid());
                                                weworkKfRelation.setServicerId(weKfSyncMsgEvent.getNewServicerUserid());
                                                weworkKfRelation.setCreateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfRelationMapper.insert(weworkKfRelation);
                                            } else {
                                                weworkKfRelation = weworkKfRelationList.get(0);
                                                weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfRelationMapper.updateStatus(weworkKfRelation);
                                            }

                                            //分配专属客服(同客服账号下所有成员)
                                            if (weworkKfRelation.getIsUpgradeMember() == 0) {
                                                UpgradeServicerDto upgradeServiceDto = new UpgradeServicerDto();
                                                upgradeServiceDto.setExternal_userid(weKfSyncMsgEvent.getExternalUserid());
                                                upgradeServiceDto.setOpen_kfid(weKfSyncMsgEvent.getOpenKfid());
                                                upgradeServiceDto.setType(1);

                                                UpGradeServiceMember upGradeServiceMember = new UpGradeServiceMember();
                                                upGradeServiceMember.setUserid(weKfSyncMsgEvent.getNewServicerUserid());
                                                upgradeServiceDto.setMember(upGradeServiceMember);

                                                WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
                                                if (weResultDto.getErrcode() == 0) {
                                                    weworkKfRelation.setIsUpgradeMember(1);
                                                    weworkKfRelationMapper.updateById(weworkKfRelation);

                                                    //将同客服账号下其余接待人员升级标志位置零
                                                    weworkKfRelationMapper.resetUpgradeMember(weworkKfRelation);
                                                }
                                            }

                                        }

                                        weworkKfCustomerMapper.updateStatus(weworkKfCustomer);

                                    }

                                }

                            } else {    //聊天消息
                                //判断用户会话是否结束(状态4)
    //                        QueryWrapper<WeworkKfCustomer> wrapperKfCustomer = new QueryWrapper<>();
    //                        wrapperKfCustomer.eq("external_userid", m.getExternalUserid()).eq("open_kfid", m.getOpenKfid());
    //                        weworkKfCustomer = weworkKfCustomerMapper.selectOne(wrapperKfCustomer);

                                Map customerMap = new HashMap<>();
                                customerMap.put("external_userid", m.getExternalUserid());
                                customerMap.put("open_kfid", m.getOpenKfid());
                                List<WeworkKfCustomer> weworkKfCustomerList = weworkKfCustomerMapper.selectByMap(customerMap);
                                if (weworkKfCustomerList.size() > 0) {
                                    weworkKfCustomer = weworkKfCustomerList.get(0);

                                    if (m.getOrigin() == 5) {
                                        userid = m.getServicerUserid();
                                    } else {
                                        userid = weworkKfCustomer.getCurrentServicerId();
                                    }

                                    //原则上只选取状态4，0是考虑到企微的API开关BUG，时间判断是为了防止定时任务BUG
                                    Map weworkKfRelationMap = new HashMap<>();
                                    weworkKfRelationMap.put("servicer_id", userid);
                                    weworkKfRelationMap.put("customer_id", m.getExternalUserid());
                                    weworkKfRelationMap.put("open_kfid", m.getOpenKfid());
                                    List<WeworkKfRelation> weworkKfRelationList = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);

                                    if (weworkKfCustomer.getStatus() == 4 || weworkKfCustomer.getStatus() == 0 || weworkKfRelationList.size()==0
                                           || System.currentTimeMillis()-weworkKfRelationList.get(0).getUpdateTime().getTime()>=170000000) {    //比48小时略
                                        //定义为进入会话事件
                                        weworkKfLog = new WeworkKfLog();
                                        weworkKfLog.setEventType("enter_session");
                                        weworkKfLog.setOpenKfid(m.getOpenKfid());
                                        weworkKfLog.setServicerId(userid);
                                        weworkKfLog.setCustomerId(m.getExternalUserid());
                                        weworkKfLog.setCreateTime(new Date(m.getSendTime() * 1000));
                                        weworkKfLog.setMsgid(m.getMsgid());

                                        //接待人员
                                        weworkKfServicer = null;
                                        Map servicerMap = new HashMap<>();
                                        servicerMap.put("userid", userid);
                                        servicerMap.put("open_kfid", m.getOpenKfid());
                                        List<WeworkKfServicer> weworkKfServicerList = weworkKfServicerMapper.selectByMap(servicerMap);
                                        if (weworkKfServicerList.size() == 0) {    //添加接待人员
                                            //新增API
                                            servicerDto.setOpen_kfid(m.getOpenKfid());
                                            List<String> ul = new ArrayList<>();
                                            ul.add(userid);
                                            servicerDto.setUserid_list(ul);

                                            servicerListResDto = weKfClient.addServicer(servicerDto);
                                            //新增成功
                                            if (servicerListResDto.getErrcode() == 0) {
                                                weworkKfServicer = new WeworkKfServicer();
                                                weworkKfServicer.setUserid(userid);
                                                weworkKfServicer.setOpenKfid(m.getOpenKfid());
                                                weworkKfServicer.setCreateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                weworkKfServicer.setStatus(1);
                                                weworkKfServicer.setIsActivate(1);
                                                weworkKfServicerMapper.insertWeworkKfServicer(weworkKfServicer);

                                                //重新获取数据（主键id）
                                                weworkKfServicer = (WeworkKfServicer) weworkKfServicerMapper.selectByMap(servicerMap).get(0);

                                            } else {
                                                weworkKfLog.setSysTime(new Date());
                                                weworkKfLog.setNote("添加接待人员失败——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                            }

                                        } else {
                                            weworkKfServicer = weworkKfServicerList.get(0);

                                            if (weworkKfServicer.getIsActivate() == 0) {    //未激活
                                                //再次添加接待人员
                                                servicerDto.setOpen_kfid(m.getOpenKfid());
                                                List<String> ul = new ArrayList<>();
                                                ul.add(userid);
                                                servicerDto.setUserid_list(ul);

                                                servicerListResDto = weKfClient.addServicer(servicerDto);
                                                //新增成功
                                                if (servicerListResDto.getErrcode() == 0) {
                                                    weworkKfServicer.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                    weworkKfServicer.setIsActivate(1);
                                                    weworkKfServicerMapper.updateStatus(weworkKfServicer);
                                                } else {
                                                    weworkKfLog.setSysTime(new Date());
                                                    weworkKfLog.setNote("添加接待人员失败(曾被添加)——" + servicerListResDto.getErrcode().toString() + ": " + servicerListResDto.getErrmsg());
                                                    weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);
                                                }
                                            }

                                        }

                                        //接待人员状态正常
                                        if (weworkKfServicer != null) {
                                            if (weworkKfServicer.getStatus() == 1) {
                                                //分配会话
                                                serviceStateTransDto.setOpen_kfid(m.getOpenKfid());
                                                serviceStateTransDto.setService_state(3);
                                                serviceStateTransDto.setExternal_userid(m.getExternalUserid());
                                                serviceStateTransDto.setServicer_userid(userid);

                                                serviceStateTransResDto = weKfClient.transServiceState(serviceStateTransDto);
                                                if (serviceStateTransResDto.getErrcode() == 0) {    //分配成功
                                                    //标记客户状态为"会话中"，并标记当前所属客服
                                                    weworkKfCustomer.setCurrentServicerId(userid);
                                                    weworkKfCustomer.setStatus(3);
                                                    weworkKfCustomer.setUpdateTime(new Date(m.getSendTime() * 1000));

                                                    //客户与客服关联(分配成功才关联)
    //                                QueryWrapper<WeworkKfRelation> wrapperKfRelation = new QueryWrapper<>();
    //                                wrapperKfRelation.eq("servicer_id", userid).eq("customer_id", m.getExternalUserid());
    //                                weworkKfRelation = weworkKfRelationMapper.selectOne(wrapperKfRelation);

                                                    //(位置上移)
    //                                                Map weworkKfRelationMap = new HashMap<>();
    //                                                weworkKfRelationMap.put("servicer_id", userid);
    //                                                weworkKfRelationMap.put("customer_id", m.getExternalUserid());
    //                                                weworkKfRelationMap.put("open_kfid", m.getOpenKfid());
    //                                                List<WeworkKfRelation> weworkKfRelationList = weworkKfRelationMapper.selectByMap(weworkKfRelationMap);
                                                    if (weworkKfRelationList.size() == 0) {
                                                        weworkKfRelation = new WeworkKfRelation();
                                                        weworkKfRelation.setOpenKfid(m.getOpenKfid());
                                                        weworkKfRelation.setCustomerId(m.getExternalUserid());
                                                        weworkKfRelation.setServicerId(userid);
                                                        weworkKfRelation.setCreateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelationMapper.insert(weworkKfRelation);

                                                        //重新获取
                                                        weworkKfRelation = (WeworkKfRelation) weworkKfRelationMapper.selectByMap(weworkKfRelationMap).get(0);

                                                    } else {
                                                        weworkKfRelation = weworkKfRelationList.get(0);
                                                        weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                                        weworkKfRelationMapper.updateStatus(weworkKfRelation);
                                                    }

                                                    //分配专属客服(同客服账号下所有成员)
                                                    if (weworkKfRelation.getIsUpgradeMember()==0) {
                                                        UpgradeServicerDto upgradeServiceDto = new UpgradeServicerDto();
                                                        upgradeServiceDto.setExternal_userid(m.getExternalUserid());
                                                        upgradeServiceDto.setOpen_kfid(m.getOpenKfid());
                                                        upgradeServiceDto.setType(1);

                                                        UpGradeServiceMember upGradeServiceMember = new UpGradeServiceMember();
                                                        upGradeServiceMember.setUserid(userid);
                                                        upgradeServiceDto.setMember(upGradeServiceMember);

                                                        WeResultDto weResultDto = weKfClient.upgrade_service(upgradeServiceDto);
                                                        if(weResultDto.getErrcode()==0){
                                                            weworkKfRelation.setIsUpgradeMember(1);
                                                            weworkKfRelationMapper.updateById(weworkKfRelation);

                                                            //将同客服账号下其余接待人员升级标志位置零
                                                            weworkKfRelationMapper.resetUpgradeMember(weworkKfRelation);
                                                        }
                                                    }

                                                } else {    //分配失败
                                                    weworkKfLog.setNote("分配客户失败——" + serviceStateTransResDto.getErrcode().toString() + ": " + serviceStateTransResDto.getErrmsg());

                                                    //此处酌情处理(暂将所有分配异常客户状态置0)
                                                    weworkKfCustomer.setStatus(0);
                                                }

                                                weworkKfLog.setSysTime(new Date());
                                                weworkKfLogMapper.insertWeworkKfLog(weworkKfLog);

                                            } else {
                                                //记录此情形
                                                weworkKfLog.setSysTime(new Date());
                                                weworkKfLog.setNote("分配客户失败——接待人员不在接待状态");
                                            }
                                        }

                                    } else {
                                        //更新最近聊天时间
                                        weworkKfRelation = weworkKfRelationList.get(0);
                                        weworkKfRelation.setUpdateTime(new Date(m.getSendTime() * 1000));
                                        weworkKfRelationMapper.updateStatus(weworkKfRelation);
                                    }

                                    weworkKfCustomerMapper.updateStatus(weworkKfCustomer);
                                }

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    hasMore = syncMsgResDto.getHasMore();
                    cursorCache.setCacheObject(TenantContextHolder.getTenantCode(), syncMsgResDto.getNextCursor());

                } else {
                    hasMore = 0;
                }

            } while (hasMore == 1);

//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }
}